using Internal;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Daemon;
using Daemon.Common;
using Daemon.Common.Tree;
using Daemon.Model;
using Daemon.Repository.Contract;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Daemon.Common.Auth;
using Daemon.Common.Cache;
using Daemon.Middleware;
using Daemon.Common.Attribute;
using Daemon.Data.Infrastructure.Auth;
using Microsoft.AspNetCore.Hosting;
using Daemon.Common.Generator;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
using Daemon.Common.Helpers;
using System.Net.Http;
using Microsoft.AspNetCore.SignalR;
using DaemonAPI.Hubs;

namespace DaemonAPI
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class TestController : ControllerBase
    {
        private readonly IAdminUserRepository _adminUserRepository;

        private readonly IDaemonDistributedCache _cache;

        private readonly IWebHostEnvironment _env;

        private readonly IHttpClientFactory _httpClientFactory;

        private readonly ICommonCityRepository _commonCityRepository;

        private IHubContext<UserOrderHub> _orderHubContext;

        private readonly ApiDBContent _context;

        private TestStatic _static;

        public TestController(ApiDBContent context, IHubContext<UserOrderHub> orderHubContext, IAdminUserRepository adminUserRepository, IDaemonDistributedCache cache, IWebHostEnvironment env, ICommonCityRepository commonCityRepository, IHttpClientFactory httpClientFactory)
        {
            _adminUserRepository = adminUserRepository;
            _cache = cache;
            _env = env;
            _httpClientFactory = httpClientFactory;
            _commonCityRepository = commonCityRepository;
            _orderHubContext = orderHubContext;
            _static = new TestStatic();
            _context = context;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultModel> Test(string schema)
        {
            Console.WriteLine(_static);
            List<FuelHistory> results = new List<FuelHistory>();

            // Populate the list with sample data
            for (int i = 0; i < 50005; i++)
            {
                results.Add(new FuelHistory()
                {
                    Id = i,
                    EquipmentId = 10,
                    EventDateTime = DateTime.Now.AddMinutes(-i), // Different timestamps for demonstration
                    MeterReadingValue = i,
                    AddtionalValue = i
                });
            }

            // Sort results once, by EventDateTime and Id in descending order
            var sortedResults = results
                .OrderByDescending(r => r.EventDateTime)
                .ThenByDescending(r => r.Id)
                .ToList();

            FuelHistory fuelEconomy = null;

            foreach (var r in sortedResults)
            {
                foreach (var entity in sortedResults)
                {
                    // Find the first record with the same EventDateTime but a smaller Id
                    fuelEconomy = sortedResults
                        .FirstOrDefault(r => r.EventDateTime == entity.EventDateTime && r.Id < entity.Id);

                    if (fuelEconomy != null)
                        break; // Exit if we found a matching record

                    // If no match with the same EventDateTime, find the first with a different EventDateTime
                    fuelEconomy = sortedResults.FirstOrDefault(r => r.EventDateTime != entity.EventDateTime);
                    if (fuelEconomy != null)
                        break;
                }
            }

            // Now `fuelEconomy` holds the last matching record
            Console.WriteLine(fuelEconomy?.Id);


            // List<CommonCity> addList = new List<CommonCity>();
            // string fileContent = System.IO.File.ReadAllText(@"C:\Users\Transfinder\Desktop\citydata.txt");
            // var cityData = GetCommonCity(JsonConvert.DeserializeObject<List<CityData>>(fileContent), 0, 0, addList);
            // _commonCityRepository.AddRangeByDBContext(cityData);
            var unselect = _context.AdminUser.Where(r => r.Id > 1);
            var user = _context.AdminUser.AsEnumerable().Select(r => new { Id = r.Id, UserName = r.UserName, Phone = r.Phone });
            var node = _context.SystemMenus.First(r => r.Id == 176);
            var children = GetChildren(_context.SystemMenus.ToList(), node.Id);
            // var user1 = _context.AdminUser.Select(r => new AdminUser() { Id = r.Id, UserName = r.UserName, Phone = r.Phone });
            return new ResultModel(System.Net.HttpStatusCode.OK, "", user);
        }

        [HttpGet]
        [AllowAnonymous]
        public ResultModel TestSignalr()
        {
            _orderHubContext.Clients.Groups("daemon").SendAsync("ReceiveMessage", "test11", 11);
            return new ResultModel();
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultModel> CapScreen()
        {
            var options = new ChromeOptions();
            options.AddArgument("--headless");
            options.AddArgument("--start-maximized");

            using (var driver = new ChromeDriver(options))
            {
                driver.Navigate().GoToUrl("http://www.baidu.com");
                var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                screenshot.SaveAsFile("screenshot.png");

                Console.WriteLine("Screenshot saved successfully.");
            }
            return new ResultModel();
        }

        public class FuelHistory
        {
            public int Id { get; set; }

            public int EquipmentId { get; set; }

            public decimal? MeterReadingValue { get; set; }

            public decimal? AddtionalValue { get; set; }

            public DateTime EventDateTime { get; set; }
        }

        public class Role
        {
            public int Id { get; set; }

            public string Name { get; set; }
        }

        public class CityData
        {
            public int value { get; set; }

            public string label { get; set; }

            public List<CityData> children { get; set; }
        }

        public class TestStatic
        {
            private readonly AdminUser _adminUser = new AdminUser()
            {
                UserName = Guid.NewGuid().ToString(),
            };
        }

        private List<SystemMenu> GetChildren(IEnumerable<SystemMenu> nodes, int parentId, List<SystemMenu> result = null)
        {
            if (result == null)
            {
                result = new List<SystemMenu>();
            }

            var children = nodes.Where(r => r.FatherId == parentId);
            if (children.Any())
            {
                result.AddRange(children);
                foreach (var child in children)
                {
                    GetChildren(nodes, child.Id, result);
                }
            }

            return result;
        }

        private List<CommonCity> GetCommonCity(List<CityData> data, int level, int parentId, List<CommonCity> addList)
        {
            level++;
            data.ForEach(city =>
            {
                CommonCity entity = new CommonCity();
                entity.Label = city.label;
                entity.Value = city.value;
                entity.Level = level;
                entity.ParentId = parentId;
                addList.Add(entity);
                if (city.children != null && city.children.Count > 0)
                {
                    GetCommonCity(city.children, level, city.value, addList);
                }
            });

            return addList;
        }

        private async Task<List<CityData>> GetCity()
        {
            var result = new List<CityData>();
            var url = "https://ym.dsppt.top/index.php/channel/shop/get-city?type=3";
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Add("Cookie", "PHPSESSID=99nkohua1eb4u16avldbe6rg3m");
            client.BaseAddress = new Uri(url);
            var response = await client.GetAsync(url);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();
                result = JsonConvert.DeserializeObject<List<CityData>>(content);
            }

            return result;
        }
    }
}